/**
 * 设置ajax请求403后,跳转登录页面
 * ==============================================================================
 */
$.ajaxSetup({
    complete: function (XMLHttpRequest, textStatus) {
        var redirect = XMLHttpRequest.getResponseHeader("Redirect");
        if (redirect == "true") {
            window.location.href = XMLHttpRequest.getResponseHeader("RedirectUrl");
        }

        if (XMLHttpRequest.status == Messages.HTTP_STATUS.SUCCESS && textStatus == 'parsererror' && XMLHttpRequest.responseText.indexOf('<title>登录</title>')) {
            window.location.href = ctx + '/login';
        }
    },

    statusCode: {
        302: function () {
            ELEMENT.Message.error(Messages.PLEASE_LOGIN);
            setTimeout(function () {
                window.open(ctx + '/login', '_top');
            }, 3000);
        },
        403: function () {
            ELEMENT.Message.error(Messages.PLEASE_LOGIN);
            setTimeout(function () {
                window.open(ctx + '/login', '_top');
            }, 3000);
        },
    }
})

$(function () {
    autoImag();
    window.onresize = function () {
        autoImag();
    }

    // 我想拍关闭
    $('.Photograph .close').click(function () {
        $('.Photograph').hide();
    });

    // 我想拍弹出框关闭
    $('.my-xp-modal .my-xp-close').click(function () {
        $('.my-xp-modal').hide();
        $('.my-xp-modal-bg').hide();
    });

    // 头部导航点击变色效果
    $('.NavItem').click(function () {
        $(this).addClass('NavItem_selected').siblings('.NavItem').removeClass('NavItem_selected');
    })

    // 首页头部用户登录之后点击下拉菜单
    $('.login_already').hover(function () {
        $(this).find('ul').stop().slideDown(300);
    }, function () {
        $(this).find('ul').stop().slideUp(300);
    });


    // 首页作品墙鼠标滑动效果
    $('.index_row_div_lg').hover(function () {
        $(this).find('.show_info').find('.img_info').stop().animate({'bottom': '0px'}, 300);
    }, function () {
        $(this).find('.show_info').find('.img_info').stop().animate({'bottom': '-128px'}, 300);
    });

    // 首页右侧导航点击回到顶部
    $('.clickTop').click(function () {
        $('html,body').animate({scrollTop: 0}, 300);
    });

    // 婚恋简介底部分页点击效果
    $('.love_container_page li').click(function () {
        $(this).addClass('on').siblings().removeClass('on');
    });

    // 搜索框点击获取焦点和失去焦点
    $('.love_container .love_container_title_r input').focus(function () {
        $(this).parent().css('border-color', '#ff5722');
    }).blur(function () {
        $(this).parent().css('border-color', '#bebebe');
    });

    // 私人订制导演、编剧上方单项选择按钮
    $('.my_row label input[type="radio"]').click(function () {
        $(this).parent().parent().addClass('on');
        $(this).parent().parent().siblings('.my_row').removeClass('on');
        // $(this).parent().parent().siblings('.my_row').addClass('ban');
    });

    // 私人订制模态窗背景高度
    var documentHeight = $(document).height();
    $('.window_bg').css('height', documentHeight - 70 + 'px');

    // 私人订制模态窗步骤指示
    $('.window_box_one .btn:eq(0)').click(function () {
        $('body,html').animate({"scrollTop": 1939}, 500);
        $('.window_box_two').show();
        $('.window_box_one').hide();
    });
    $('.window_box_one .btn:eq(1)').click(function () {
        $('.window_box_one').hide();
        $('.window_bg').hide();
        $('.message_item_bz,.message_item_con').show();
    });
    $('.window_box_two .btn').click(function () {
        $('body,html').animate({"scrollTop": 2984}, 500);
        $('.window_box_three').show();
        $('.window_box_two').hide();
    });
    $('.window_box_three .btn').click(function () {
        $('.window_box_three').hide();
        $('.window_box_four').show();
    });
    $('.window_box_four .btn').click(function () {
        $('.window_box_four').hide();
        $('.window_bg').hide();
        $('.message_item_bz,.message_item_con').show();
    });

    // 右侧边栏步骤按钮点击
    $('.message_item_bz').click(function () {
        $('.message_item_con').show();
    });
    $('.message_item_con .btn').click(function () {
        $('.message_item_con').hide();
    });
    
    // 首页-为什么选择巨桃游娱-鼠标放上滑动
	$('.index-content-2 .box-row li').hover(function(){
		$(this).find('.modle').stop().animate({'top':'0px'},300);
	},function(){
		$(this).find('.modle').stop().animate({'top':'230px'},300);
	});


    /**
     * 获取短信验证码
     */
    $('.get-sms-code').click(function () {
        if (!!$(this).attr('disabled')) {
            return false;
        }
        var mobile = $('.mobile-for-sms-code').val();
        if (!mobile) {
            ELEMENT.Message.error(Messages.PLEASE_ENTER_MOBILE);
            return false;
        }
        var wait = 60;
        var _self = this;
        $.ajax({
            url: '/api/sms_validate_code?mobile=' + mobile,
            type: 'get',
            async: false,
            dataType: 'json',
            beforeSend: function() {
                _self.disabled = true;
            },
            success: function (result) {
                if (result.status == Messages.HTTP_STATUS.SUCCESS) {
                    var temp = setInterval(function () {
                        _self.disabled = true;
                        _self.innerText = '等待' + wait + '秒';
                        if (wait == 0) {
                            _self.disabled = false;
                            _self.innerText = '发送验证码';
                            clearInterval(temp);
                        } else {
                            wait--;
                        }
                    }, 1000);
                } else {
                    _self.disabled = false;
                    ELEMENT.Message.error(result.error);
                }
            },
            error: function (e) {
                _self.disabled = false;
                ELEMENT.Message.error(Messages.ERROR);
            }
        })
    })
});

/**
 * 自动调图片尺寸
 */
function autoImag() {
    if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
        $('.div_row_index').css("height", $('.div_row_index').width() * 0.7 + 'px');
        $('.div_row_video').css("height", $('.div_row_video').width() * 0.7 + 'px');
        $('.div_row_private').css("height", $('.div_row_private').width() * 0.7 + 'px');
        $('.div_row_team').css("height", $('.div_row_team').width() * 1.3 + 'px');
        $('.header_img').css("height", $('.header_img').width() * 1.1 + 'px');
        $('.info_img').css("height", $('.info_img').width() * 0.7 + 'px');
        $('.team_div').css("height", $('.team_div').width() * 1.7 + 'px');
        $('.screen_phone_img').css("height", $('.screen_phone_img').width() * 0.6 + 'px');
    } else {
        $('.div_row_index').css("height", $('.div_row_index').width() * 1.3 + 'px');
        $('.div_row_video').css("height", $('.div_row_video').width() * 0.7 + 'px');
        $('.div_row_private').css("height", $('.div_row_private').width() * 1.3 + 'px');
        $('#min_div').css("min-height", $('.div_row_private').width() * 1.4 + 'px');
        $('#min_div_child').css("height", $('.div_row_private').width() * 1.4 + 'px');
        $('.div_row_team').css("height", $('.div_row_team').width() * 1.3 + 'px');
        $('.header_img').css("height", $('.header_img').width() * 1.0 + 'px');
        $('.info_img').css("height", $('.info_img').width() * 0.7 + 'px');
    }
}

/**
 * 打开模态框
 * @param column
 */
function openProup(column) {
    $('#img_area').children().remove();

    if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent) && column == 'telephone') column = 'mobiletelephone';

    $.ajax({
        type: 'get',
        url: '/sysconfig/api/get?column=' + column,
        dataType: 'json',
        success: function (result) {
            if (result.status == 200) {
                // if mobile device
                if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent) && column == 'mobiletelephone') {
                    window.location.href = 'tel://' + result.data.value;
                } else if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent) && column == 'consult') {
                    $('#nb_invite_ok').click();
                } else {
                    var img = new Image();
                    img.src = uploadServer + result.data.value;
                    img.style.width = '100%';
                    img.style.height = '100%';
                    $('#img_area').html(img);
                    $("#popup").show(100);
                }
            }
        }
    });
}

/**
 * phone of right site
 */
function callPhone() {
    var xgfPhone = "400-006-9858";
    window.location.href = 'tel:' + xgfPhone;
}

/**
 * common constants
 * ==============================================================================
 */
/**
 *
 */
var OrderStatusDict = {
    fresh: function (type) {
        $.get('/dict/api/list/' + type, function (result) {
            window.localStorage.setItem(type, JSON.stringify(result.data));
        })
    },
    
    get: function (value, type) {
        var temp = window.localStorage.getItem(type);
        temp = JSON.parse(temp);
        for (var i in temp) {
            if (type == temp[i].type && value == temp[i].value) {
                return temp[i].name;
            }
        }
        return "";
    }
}

/**
 * common function
 * ==============================================================================
 */

/**
 * 上传头像回调
 * @param btnId
 * @param url
 */
function calTitleImg(btnId, url, valueInput, imgWrapper, previewPane, jcropPreview, jcropDesctroy, ratio) {
    // 销毁图片插件
    $(jcropDesctroy).click();
    $(imgWrapper).attr("style", "");
    $(imgWrapper).attr("src", uploadServer + url);
    $(jcropPreview).attr("src", uploadServer + url);
    $(valueInput).val(url);

    var img = new Image();
    img.src = uploadServer + url;
    img.onload = function () {
        var tagName = $(valueInput).prop('name');
        var realHeight = img.height;
        var realWidth = img.width;
        if (realHeight >= realWidth && realHeight > 300) {
            var height = 300;
            var width = height * realWidth / realHeight;
            $(imgWrapper).attr("height", height);
            $(imgWrapper).attr("width", width);
            $('#' + tagName + '_width').val(Math.ceil(width));
            $('#' + tagName + '_height').val(height);
        } else if (realHeight < realWidth && realWidth > 300) {
            var width = 300;
            var height = width * realHeight / realWidth;
            $(imgWrapper).attr("height", height);
            $(imgWrapper).attr("width", width);
            $('#' + tagName + '_width').val(width);
            $('#' + tagName + '_height').val(Math.ceil(height));
        } else {
            var height = realHeight;
            var width = realWidth;
            $(imgWrapper).attr("height", height);
            $(imgWrapper).attr("width", width);
            $('#' + tagName + '_width').val(Math.ceil(width));
            $('#' + tagName + '_height').val(height);
        }
        editingPhotos(valueInput, imgWrapper, previewPane, jcropDesctroy, ratio);
    };
}

/**
 * 编辑图片
 */
function editingPhotos(valueInput, imgWrapper, previewPane, jcropDesctroy, ratio) {
    jQuery(function ($) {
        var jcrop_api,
            boundx,
            boundy,
            $preview = $('.preview-pane'),
            $pcnt = $(previewPane + ' .preview-container'),
            $pimg = $(previewPane + ' .preview-container img'),
            xsize = $pcnt.width(),
            ysize = $pcnt.height();

        $(imgWrapper).Jcrop({
            onChange: updatePreview,
            onSelect: updatePreview,
            allowSelect: false,//是否允许新选框
            minSize: [50, 50],//选框最小尺寸
            aspectRatio: ratio
        }, function () {
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];
            jcrop_api = this;
            jcrop_api.animateTo([80, 50, 80, 20]);
            $preview.appendTo(jcrop_api.ui.holder);
        });

        function updatePreview(c) {
            var tagName = $(valueInput).prop('name');
            $('#' + tagName + '_left').val(c.x);
            $('#' + tagName + '_top').val(c.y);
            $('#' + tagName + '_DropWidth').val(Math.round(c.w) - 1);
            $('#' + tagName + '_DropHeight').val(Math.round(c.h) - 1);
            if (parseInt(c.w) > 0) {
                var rx = xsize / c.w;
                var ry = ysize / c.h;
                $pimg.css({
                    width: Math.round(rx * boundx) + 'px',
                    height: Math.round(ry * boundy) + 'px',
                    marginLeft: '-' + Math.round(rx * c.x) + 'px',
                    marginTop: '-' + Math.round(ry * c.y) + 'px'
                });
            }
        }

        $(jcropDesctroy).click(function (e) {
            jcrop_api.destroy();
            return false;
        });
    });
}

/**
 * 前台专用图片上传
 * @param btnId 上传组件的ID
 * @param param 图片上传目录名
 * @param callback 上传成功后的回调函数，函数接收一个参数（上传图片的URL）
 */
function webImageUpload(btnId, param, callback, valueInput, imgWrapper, previewPane, jcropPreview, jcropDesctroy, ratio) {
    var uploadbutton = KindEditor.uploadbutton({
        button: KindEditor('#' + btnId + '')[0],
        fieldName: "uploadfile",
        url: uploadServer + '/image/gok4?&param=' + param + '&fileType=jpg,gif,png,jpeg',
        afterUpload: function (data) {
            console.log(data)
            if (data.error == 0) {
                var url = KindEditor.formatUrl(data.url, 'absolute');//absolute,domain
                $('#' + btnId).addClass('')
                callback(btnId, url, valueInput, imgWrapper, previewPane, jcropPreview, jcropDesctroy, ratio);
            } else {
                ELEMENT.Message.info(data.message);
            }
        },
        afterError: function (str) {
            console.error(str);
            ELEMENT.Message.info('自定义错误信息: ' + str);
        }
    });
    uploadbutton.fileBox.change(function (e) {
        uploadbutton.submit();
    });
}